package clam.apps.adu.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TimeZone;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import clam.apps.adu.metier.MyViewBinder;
import clam.apps.adu.metier.Story;

public class DernieresAnecdotesActivity extends Activity
{
	private MenuLateral			menu;
	private ListView			_activityList;
	private ArrayList<Story>	storys;
	private String				_icon = String.valueOf(R.drawable.icon);
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		// rend l'icone de l'actionBar cliquable afin de faire apparaitre le menu latéral
		this.getActionBar().setDisplayHomeAsUpEnabled(true);
		
		// charge le layout des dernieres anecdotes
		this.setContentView(R.layout.activity_vie_merde_etudiant);
		
		// affiche l'ActionBar
		this.getActionBar().show();
		
		// instancie le menu latéral
		this.menu = new MenuLateral(this);
		
		// on récupère la ListeView
		this._activityList = (ListView) this.findViewById(R.id.listView1);
		
		// on récupére toutes les Story
		this.update();
		
		if(!checkConnect())
		{	
			Log.i("Connexion", "Connexion fail");
			Toast.makeText(this.getBaseContext(),
					this.getString(R.string.erreur_connexion), Toast.LENGTH_LONG)
					.show();
			this._activityList.setVisibility(View.INVISIBLE);
		}
		else
			// toast "Dernières anecdotes"
			Toast.makeText(getBaseContext(),
					getString(R.string.dernieres_anecdote), Toast.LENGTH_SHORT)
					.show();
	}
	
	private HashMap<String, Object> fillHashMap(String theme, String date, 
			String image, String histoire, String auteur, String etablissement)
	{
		HashMap<String, Object> item = new HashMap<String, Object>();
		if(!image.equals("aucune") || image.equals("") )
		{
			Bitmap bitmap = null;
			try {
				bitmap = BitmapFactory.decodeStream((InputStream)new URL(image).getContent());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			item.put("iv_image", bitmap);
		}
		else
			item.put("iv_image", String.valueOf(this._icon));
		item.put("tv_theme", theme);
		item.put("tv_date", date);
		item.put("tv_anecdote", histoire);
		item.put("tv_auteur", auteur);
		item.put("tv_etablissement", etablissement);
		
		return item;
	}
	
	// fonction permettant de charger toutes les anecdotes
	private void update()
	{
		this._activityList.setVisibility(View.VISIBLE);
		this.storys = Story.findByEtat("Validée");
		
		// ArrayList des storys
		ArrayList<HashMap<String, Object>> appItemList = new ArrayList<HashMap<String, Object>>();
		
		// format de la date
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:00"));
		
		for (Story s : this.storys)
			appItemList.add(this.fillHashMap(s.getTheme().getLibelle(), sdf.format(s.getDate()),
								s.getPhoto(), s.getTexte(), s.getLogin(), s.getEtablissement().getSite().getLibelle()	+ " " + s.getEtablissement().getLibelle()));
		
		SimpleAdapter itemsAdapter = new SimpleAdapter(this.getBaseContext(),
				appItemList, R.layout.anecdote_item, new String[] {
						"tv_theme", "tv_date", "iv_image", "tv_anecdote",
						"tv_auteur", "tv_etablissement"
				}, new int[] {
						R.id.tv_theme, R.id.tv_date, R.id.iv_image,
						R.id.tv_anecdote, R.id.tv_auteur, R.id.tv_etablissement });
		
		itemsAdapter.setViewBinder(new MyViewBinder());
		
		// mise à jour de la liste
		this._activityList.setAdapter(itemsAdapter);
	}
	
	// creer le menu dans l'actionBar
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		this.getMenuInflater().inflate(R.menu.vie_merde_etudiant, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// permet de valider la selection du menu
		if (this.menu.getDrawerToggle().onOptionsItemSelected(item))
			return true;
		
		switch (item.getItemId())
		{
			case R.id.menu_refresh:
				this.update();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
		
	}
	
	// test de la connexion
	public boolean checkConnect()
	{
		ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
		return (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected());
	}
}
